package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;

import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;



@Service
public class RegionServiceImpl implements IRegionService {


    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //查询对象
        Query query = new Query();
        //查询总条数
        long totalCount = mongoTemplate.count(query, Region.class);

        //使用PageRequest.of方法
        //第一个参数：当前页（从0开始算第一页）
        //第二个参数：每页显示的条数
        //第三个参数：排序规则
        //第四个参数：排序字段
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
         query.with(pageable);
        List<Region> regions = mongoTemplate.find(query, Region.class);
        return new PageImpl(regions,pageable,totalCount);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if(StringUtils.hasLength(region.getId())){
            this.update(region);
        }else {
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(int hot, String id) {
        //先查询需要修改的指定数据
        Region region = this.get(id);
        //设置对应的修改字段
        region.setIshot(hot);
        //执行修改
        this.update(region);
    }

    @Override
    public List<Region> hotRegion() {
        return  regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
    }


}
